package com.niodata.dp.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SerializeUtil {

  public static byte[] serialize(Object object) throws IOException {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(baos)) {
      oos.writeObject(object);
      return baos.toByteArray();
    }
  }

  public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
    try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
          ObjectInputStream ois = new ObjectInputStream(bais)) {
      return ois.readObject();
    }
  }

  /**
   * object to map.
   */
  public static Map<String, Object> introspect(Object obj) throws Exception {
    Map<String, Object> result = new HashMap();
    BeanInfo info = Introspector.getBeanInfo(obj.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
      Method reader = pd.getReadMethod();
      if (reader != null && !pd.getName().equalsIgnoreCase("class")) {
        result.put(pd.getName(), reader.invoke(obj));
      }
    }
    return result;
  }
}
